package com.example.demo.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.entity.Role;
import com.example.demo.mapper.RoleMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.List;


/**
 * @author:王声基
 * @date:2019/12/25
 * @decription:角色控制层
 */
@Api(tags = "role")
@RestController
@EnableSwagger2
public class RoleController {

    @Autowired
    private RoleMapper roleMapper;

    //添加角色
    @ApiOperation(value ="添加角色")
    @PutMapping("/insertRole")
    @Transactional
    public int insertRole(String roleName,String description){
        if(roleMapper.selectRoleByName(roleName)!=null)
            return roleMapper.insertRole( roleName, description);
        return 0;
    }
    //角色查询
    @ApiOperation(value ="查询角色")
    @PutMapping("/selectRole")
    public JSONArray selectRole(String roleName){
        List<Role> list = roleMapper.selectRoleByName(roleName);
        JSONArray jsonArray=new JSONArray();
        for (Role role:list) {
            JSONObject jsonObject=new JSONObject();
            jsonObject.put("id",role.getRoleId());
            jsonObject.put("name",role.getRoleName());
            jsonObject.put("description",role.getDescription());
            jsonObject.put("人数",roleMapper.selectCountOfRoleById(role.getRoleId()));
            jsonArray.add(jsonObject);
        }
        return jsonArray;
    }
    //删除角色
    @ApiOperation(value ="删除角色")
    @PutMapping("/deleteRole")
    public int deleteRole(int roleId){
        if (roleMapper.selectCountOfRoleById(roleId)!=0)
        {
            return 0;
        }
        return roleMapper.deleteRole(roleId);
    }
}
